package com.example.demo.controller;

import com.example.demo.comm.RedisCache;
import com.example.demo.comm.Result;
import com.example.demo.comm.ResultUtils;
import com.example.demo.comm.ThreadPoolComponent;
import com.example.demo.utils.MultiPartDownLoadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;
import java.util.concurrent.ExecutorService;

/**
 * 多部件降负荷控制器
 *
 * @author dlp
 * @date 2024/09/06
 */
@RestController
@RequestMapping("/multiPartDownLoad")
public class MultiPartDownLoadController {

    @Autowired
    private RedisCache redisCache;


    /**
     * 完成下载多线程
     *
     * @return
     */
    @PostMapping("/downLoad")
    //todo 重复提交
    public Result<Boolean> complete(String downloadId,String serverPathUrl , String localDirectory){
        if (downloadId==null){
            return  ResultUtils.error("downloadId is null");
        }
        if (serverPathUrl==null){
            return  ResultUtils.error("serverPathUrl is null");
        }
        if (localDirectory==null){
            return  ResultUtils.error("localDirectory is null");
        }
        //异步加载
        new Thread(()->{
            MultiPartDownLoadUtils.downLoad(downloadId,serverPathUrl,localDirectory);
        }).start();
        return ResultUtils.ok(true);
    }


    /**
     * 获取下载进度
     *
     * @return
     */
    @GetMapping("/getSpeedOfProgress/{downloadId}")
    public Result<Float> getSpeedOfProgress(@PathVariable("downloadId")String downloadId){
        //如果使用换成redis进行存储
        Integer completedQuantity = (Integer) Optional.ofNullable(redisCache.getCacheObject(downloadId)).orElse(0);
        Integer count = redisCache.getCacheObject(downloadId+"_count");
        return ResultUtils.ok(((float)(count-completedQuantity)/count)*100);
    }


}
